;(function(window, document) {
    angular
        .module('app')
        .directive('buyBtn', buyBtn);

    buyBtn.$inject = [
        'uidFactory',
        'payOnedayFactory',
        'WebViewJavascriptBridgeFactory',
        'payPayokFactory',
        'randomWordFactory',
        'userAgentFactory',
        'globalService',
        '$cookies',
        '$state'
    ];

    function buyBtn (uidFactory, payOnedayFactory, WebViewJavascriptBridgeFactory, payPayokFactory, randomWordFactory, userAgentFactory, globalService, $cookies, $state) {
        return {
            restrict: 'AE',
            scope: { // css类, 按钮状态, 帐号天数id, 帐号天数价格
                className: '@',
                status: '=',
                dayid: '=',
                money: '='
            },
            template: [
                '<a href="javascript: void(0);" class="{{cls}}">',
                '{{ name }}',
                '</a>'
            ].join(''),
            replace: true,
            link: function(scope, elem, attr) {
                var uid = uidFactory.getUid();
                var money = 0;
                var orderid = 0;

                scope.name = parseInt(scope.status) === 1 ? '立即购买' : '已经抢光';
                scope.cls = parseInt(scope.status) === 1 ? scope.className : scope.className + ' disabled';

                elem.on('click', function() {

                    if (!uid) {
                        alert('下载账号伴侣手机APP，更多免费账号天天享！');
                        if (userAgentFactory.getOS() === 'ios') {
                            location.href = 'https://itunes.apple.com/us/app/zhang-hao-ban-lu/id992488773?l=zh&ls=1&mt=8';
                        } else if (userAgentFactory.getOS() == 'android') {
                            location.href = 'https://www.pgyer.com/CTcd';
                        } else {
                            location.href = 'http://mp.weixin.qq.com/s?__biz=MzA3MjU0NDU3Ng==&mid=503801138&idx=1&sn=6f9c4a4c9e7d648304163fba94ff375a&scene=23&srcid=0715SrVJZhleC2rBVsBZNKw5#rd';
                        }
                        return;
                    }

                    if (scope.status) {
                        // 将dayid赋给全局变量以便android调用以便支付完成后的页面跳转所需参数
                        globalService.dayid = scope.dayid;

                        pay(scope.dayid, scope.money);
                    }
                });

                function pay (_dayid, _money) {
                    money = _money;
                    payOnedayFactory.setUid(uid);
                    payOnedayFactory.setDayid(_dayid);
                    payOnedayFactory.payOnedayPromise().then(payOnedayPromiseSuccess, payOnedayPromiseFail);
                }

                function payOnedayPromiseSuccess (data) {
                    // alert(angular.toJson(data));
                    switch (data.returncode) {
                        case 0:
                            // 订单号
                            orderid = data.orderid;
                            // 将订单号赋给全局变量以便android调用接口时进行订单号验证
                            globalService.orderid = data.orderid;

                            if (userAgentFactory.getOS() === 'ios') {
                                WebViewJavascriptBridgeFactory.init(function(bridge) {
                                        // web -> ios
                                        bridge.callHandler('vipbanlvPayCall', {
                                            'orderId': orderid,
                                            'price': money
                                        }, function(response) {
                                            log('JS got response', response);
                                        });

                                        // ios -> web
                                        bridge.registerHandler('vipbanlvPayCallback', window.vipbanlvPayCallback);
                                });

                            } else if (userAgentFactory.getOS() === 'android') {
                                if (typeof vipbanlvFunc == 'object') {
                                    vipbanlvFunc.vipbanlvPayCall("{\"orderId\":\""+orderid+"\",\"price\":\""+money+"\"}");
                                }
                            }
                            break;
                        case -1:
                            alert('已购买同类型账号，到期后才能再次购买哦！');
                            break;
                        case -3:
                            alert('订单状态异常!');
                            break;
                        case -999:
                            alert('系统维护升级中');
                            break;
                        default:
                            alert('系统维护升级中');
                    }
                }

                function payOnedayPromiseFail(err) {
                    alert(err);
                }

                window.vipbanlvPayCallback = function (data) {

                    if (angular.isString(data)) {
                        data = angular.fromJson(data);
                    }

                    // 判断接收到的订单号与发送的订单号是否一致
                    if (data.orderId === globalService.orderid) {
                        // 向后台发送
                        payPayokFactory.setOrderid(data.orderId);
                        payPayokFactory.setPayorderid(data.payOrderId);
                        payPayokFactory.setPaytype(data.payType);
                        payPayokFactory.setSign(data.sign);

                        payPayokFactory.payPayokPromise().then(payPayokPromiseSuccess, payPayokPromiseFail);
                    } else {
                        alert('订单号不一致');
                    }
                };

                function payPayokPromiseSuccess(data) {
                    switch (data.returncode) {
                        case 0:
                            // 生成随机数
                            var randomKey = randomWordFactory.getRandomWord(true, 8, 12);
                            $cookies.putObject(randomKey, {
                                username: data.username,
                                password: data.password
                            }, {expires: new Date(Date.now() + 1800000)});

                            // alert('dayid:' + globalService.dayid);
                            // 跳转
                            $state.go('accountDaylist.details.payok', {accountdayid: globalService.dayid, key: randomKey});
                            break;
                        case -1:
                            alert('已购买同类账号');
                            break;
                        case -2:
                            alert('签名失败');
                            break;
                        case -3:
                            alert('订单状态错误');
                            break;
                        case -999:
                            alert('系统维护升级中');
                            break;
                    }
                }

                function payPayokPromiseFail(err) {
                    alert(err);
                }
            }
        };
    }
})(window, document);
